<template>
	<view class="canvas-content">
		<view class="canvas-mask"></view>
		<view class="preview-panel">
			<view class="preview-panel-header">预览</view>
			<view class="preview-panel-body"><img v-if="tempFilePath" :style="{ height: height + 'rpx' }" class="panel-image" :src="tempFilePath" /></view>
			<view class="preview-panel-footer">
				<button @click="close">关闭</button>
				<text style="width: 2rpx;height: 50rpx;background: rgba(102, 100, 93, 0.15);margin: 20rpx 0;"></text>
				<button @click="showShare = true" :disabled="shareButton">分享</button>
			</view>
		</view>
		<!-- 分享弹窗-->
		<view class="share-pro" v-if="showShare">
			<view class="share-pro-mask" @tap="showShare = false"></view>
			<view class="share-pro-dialog" :class="showShare ? 'open' : 'close'">
				<view class="share-pro-body">
					<view class="share-item">
						<!-- #ifdef MP-WEIXIN -->
						<button open-type="share"><view class="wechat"></view></button>
						<text class="text">分享小程序给好友</text>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view @tap="share" class="wechat"></view>
						<text class="text">分享给好友</text>
						<!-- #endif -->
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<view class="share-item" @tap="downloadSharePhoto">
						<view class="font_family share-icon">&#xe600;</view>
						<text class="text">保存图片到本地</text>
					</view>
					<!-- #endif -->
					
					<!-- #ifdef H5 -->
					<view class="share-item" @tap="downloadSharePhoto">
						<view class="font_family share-icon" style="width:49px;width:49px;">
							<img style="width: 98rpx;height: 98rpx;" src="https://mall-rongchuang.oss-cn-beijing.aliyuncs.com/upload/poster.png" />
						</view>
						<text class="text">朋友圈</text>
					</view>
					<!-- #endif -->
				</view>
				<button type="default" class="share-cancel" @tap="showShare = false">取消</button>
			</view>
		</view>
		<loading ref="loading"></loading>
		<!-- #ifdef H5 -->
		<view ref="canvasContainer"></view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<canvas class="canvas" canvas-id="diaryCanvas" :style="{ width: `${canvas.width}px`, height: `${canvas.height}px` }"></canvas>
		<!-- #endif -->
	</view>
</template>

<script>
import bridgeApi from '../../common/rayBridgeSDK.js';
import Loading from '../notice/loading.vue';
import { getWxShareHref } from '../../common/utils.js';
import http, { uploadImages } from '../../common/request.js';
import mp from './mp.js'
import h5 from './h5.js'
export default {
	mixins: [
		// #ifdef MP-WEIXIN
		mp
		// #endif
		// #ifdef H5
		h5
		// #endif
	],
	components: { Loading },
	data() {
		const info = uni.getSystemInfoSync();
		return {
			ctx: undefined,
			tempFilePath: '',
			showShare: false,
			shareButton: true,
			canvas: {
				el: undefined,
				width: 750,
				height: 530,
				pixelRatio: info.pixelRatio
			},
			width: 375,
			height: 530,
			textHeight: 0,
			attrs: {
				date: [],
				radius: 20,
				fillColor: '#ffffff',
				innerLR: 0,
				innerTB: 0,
				imageUrl: '',
				posterRatio: 1.67,
				logoUrl: '',
				title: '',
				codeUrl: '',
				photoGrapher: '',
				userName: '',
				posterBgUrl: ''
			}
		};
	},
	props: {
		params: {
			type: Object
		},
		dirayId: {
			type: String
		}
	},
	watch: {
		params: {
			handler(val) {
				if (val && val.title) {
					//通过title判断是否有效
					Object.assign(this.attrs, val);
					this.$nextTick(() => {
						this.creatPoster();
					})
				}
			},
			deep: true,
			immediate: true
		}
	},
	mounted() {
		const query = uni.createSelectorQuery().in(this),
			that = this;
		query
			.select('.preview-panel-body')
			.boundingClientRect(rect => {
				that.width = rect.width;
			})
			.exec();
	},
	methods: {
		base64ToUrl(base64) {
			return uploadImages('/fastdfs/upload/multiUploadPath?_=' + Date.now(), { fileList: [{ name: 'file', uri: base64 }] }).then(result => {
				return JSON.parse(result[0]).msg;
			});
		},
		sharePoster() {
			this.downloadSharePhoto();
		},
		shareDirayAdd() {
			http('/api/cusBeautifulDiary/share/', {
				data: {
					diaryId: this.dirayId
				},
				method: 'POST'
			});
		},
		//创建海报
		async creatPoster() {
			const {
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			this.ctx = uni.createCanvasContext('diaryCanvas', this);
			// #endif
			// #ifdef H5
			this.ctx = this.createCanvas();
			// #endif
			this.masterImage = await this.getImageInfo(attrs.imageUrl);
			const textHeight = this.getDynamicHeight();
			canvas.height += textHeight + this.getImageHeight(this.masterImage, canvas, attrs);
			this.height = (canvas.height * 590) / canvas.width;
			// #ifdef H5
			this.ctx = this.createCanvas();
			// #endif
			this.$refs.loading.show('生成中');
			this.ctx.save();
			// 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
			this.roundRect(0, 0, canvas.width, canvas.height, attrs.radius, '#FFFFFF', [false, false, false, false]);
			this.ctx.restore();
			//绘制标题 top 绘制文本的y位置
			let top = attrs.innerTB;
			await this.drawLogo(top);
			top = this.drawDate(top);
			//绘制海报图片
			top = await this.drawImage(top);
			//绘制摄影师
			top = this.drawCameraMan(top);
			// 绘制标题 top 绘制文本的y位置, textHeight补位文本高度
			top = this.drawContent(top) + textHeight;
			// 小程序的名称
			top = this.drawUserName(top);
			// 绘制小程序码
			await this.drawQRCode(top);
			//生成图片
			// #ifdef MP-WEIXIN
			this.ctx.draw(true, r => {
				this.saveToImage();
			});
			// #endif
			// #ifdef H5
			this.saveToImage();
			// #endif
		},
		getDynamicHeight() {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			ctx.setFontSize(26)
			// #endif
			// #ifdef H5
			ctx.font = '26px PingFangSC-Regular';
			// #endif
			const list = attrs.title.split('\n');
			let textY = 0;
			for (let text of list) {
				if (text) {
					textY += this.drawText({
						text: text,
						left: 60,
						lineHeight: 42,
						top: textY,
						maxWidth: canvas.width - 2 * 60
					}) - textY;
					textY += 42;
				}
			}
			return textY - 42;
		},
		getImageHeight(image, canvas, attrs){
			return image.height * (canvas.width - attrs.innerLR) / image.width;
		},
		drawCameraMan(top) {
			top += 20;
			const {
				ctx,
				attrs,
				canvas
			} = this;
			ctx.save();
			// #ifdef MP-WEIXIN
			ctx.setFontSize(17)
			// #endif
			// #ifdef H5
			ctx.font = '17px PingFangSC-Regular';
			// #endif
			let textY = this.drawText({
				text: attrs.photoGrapher ? '摄影  |  ' + attrs.photoGrapher : '',
				top,
				lineHeight: 37,
				textAlign: 'center'
			});
			ctx.restore();
			return textY;
		},
		drawImage(top) {
			top += 60;
			const {
				ctx,
				attrs,
				canvas,
				masterImage
			} = this;
			let width = canvas.width;
			let height = this.getImageHeight(masterImage, canvas, attrs);
			ctx.save();
			// #ifdef MP-WEIXIN
			ctx.drawImage(masterImage.path, 0, 0, masterImage.width, masterImage.height, 0, top, width, height);
			// #endif
			// #ifdef H5
			ctx.drawImage(masterImage.image, 0, 0, masterImage.width, masterImage.height, 0, top, width, height);
			// #endif
			ctx.restore();
			return height + top;
		},
		async drawQRCode(textY) {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			if (!attrs.codeUrl) {
				return;
			}
			const info = await this.getImageInfo(attrs.codeUrl);
			if (info) {
				ctx.save();
				// #ifdef H5
				ctx.drawImage(info.image, 0, 0, info.width, info.height, (canvas.width - 120) / 2, textY + 48, 120, 120);
				// #endif
				// #ifdef MP-WEIXIN
				ctx.drawImage(info.path, 0, 0, info.width, info.height, (canvas.width - 120) / 2, textY + 48, 120, 120);
				// #endif
				ctx.restore();
			}
		},
		drawContent(top) {
			top += 61;
			const {
				ctx,
				attrs,
				canvas
			} = this;
			// #ifdef MP-WEIXIN
			ctx.setFontSize(26)
			// #endif
			// #ifdef H5
			ctx.font = '26px PingFangSC-Regular';
			// #endif
			const list = attrs.title.split('\n');
			let textY = 0;
			ctx.save();
			for (let text of list) {
				if (text) {
					textY += this.drawText({
						text: text,
						left: 60,
						lineHeight: 42,
						top: top + textY,
						maxWidth: canvas.width - 2 * 60
					}) - top - textY;
					textY += 42;
				}
			}
			ctx.restore();
			return top;
		},
		drawText({
			text = '',
			left,
			top,
			lineHeight = 46,
			maxWidth,
			textAlign = 'left',
			color = '#65645D'
		}) {
			const {
				ctx,
				canvas,
				attrs
			} = this;
			top += lineHeight / 2;
			maxWidth = maxWidth || canvas.width;
			ctx.fillStyle = color;
			// 设置垂直对齐方式
			let arrText = text.split('');
			let line = '';
			for (let i = 0; i < arrText.length; i++) {
				let textLine = line + arrText[i];
				let metrics = ctx.measureText(textLine);
				if (metrics.width > maxWidth && i > 0) {
					ctx.fillText(line, left, top);
					line = arrText[i];
					top += lineHeight;
				} else {
					line = textLine;
				}
			}

			if (textAlign === 'left') {
				ctx.fillText(line, left, top);
			} else if (textAlign === 'center') {
				ctx.textAlign = textAlign;
				ctx.fillText(line, canvas.width / 2, top);
			}
			return top;
		},
		async drawLogo(top) {
			const {
				ctx,
				attrs
			} = this;
			const left = this.canvas.width - 310 - 30;
			if (!attrs.logoUrl) {
				return;
			}
			const info = await this.getImageInfo(attrs.logoUrl);
			if (info) {
				ctx.save();
				// #ifdef MP-WEIXIN
				ctx.drawImage(info.path, 0, 0, info.width, info.height, left, top + 48, 310, 36);
				// #endif
				// #ifdef H5
				ctx.drawImage(info.image, 0, 0, info.width, info.height, left, top + 48, 310, 36);
				// #endif
				ctx.restore();
			}
		},
		drawUserName(top) {
			const {
				ctx,
				attrs,
				canvas
			} = this;
			if(attrs.userName === '' || attrs.userName === undefined) {
				return top;
			}
			ctx.save();
			//#ifdef MP-WEIXIN
			ctx.setFontSize(22)
			//#endif
			// #ifdef H5
			ctx.font = '22px PingFangSC-Regular';
			// #endif
			top += 55;
			let textY = this.drawText({
				text: attrs.userName || '',
				top,
				lineHeight: 46,
				textAlign: 'center'
			});
			ctx.restore();
			return textY;
		},
		roundRect(x, y, w, h, r, fillColor = '#ffffff', lineStatus = [true, true, true, true]) {
			const { ctx } = this;
			ctx.save();
			ctx.beginPath();
			// 绘制左上角圆弧
			if (lineStatus[0]) {
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			} else {
				// 绘制border-top
				ctx.lineTo(x + w - r, y);
			}
			// 绘制右上角圆弧
			if (lineStatus[1]) {
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			} else {
				// 不全border-top
				ctx.lineTo(x + w, y);
				// 绘制border-right
				ctx.lineTo(x + w, y + h - r);
			}
			// 绘制右下角圆弧
			if (lineStatus[2]) {
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
				// 绘制border-bottom
				ctx.lineTo(x + r, y + h);
			} else {
				// 不全border-right
				ctx.lineTo(x + w, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y + h);
			}

			// 绘制左下角圆弧
			if (lineStatus[3]) {
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
				// 绘制border-left
				ctx.lineTo(x, y + r);
			} else {
				// 不全border-right
				ctx.lineTo(x, y + h);
				// 绘制border-bottom
				ctx.lineTo(x, y);
			}
			// 填充颜色
			ctx.fillStyle = fillColor;
			ctx.fill();
			// 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore 这个很重要 不然没办法保存
			ctx.clip();
			ctx.restore();
		},
		close() {
			this.$refs.loading.hide();
			this.$emit('close');
		}
	}
};
</script>

<style lang="less" scoped>
/* 按钮去掉边框 */
button::after {
	border: none;
}
button {
	color: #66645d;
}

.canvas-content {
	.canvas-mask {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 100;
	}
	.canvas {
		position: fixed;
		top: 300%;
		// z-index: 1000;
		// transform: scale(0.3);
		// transform-origin: 0 0;
	}

	.preview-panel {
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		transform: translateY(-50%);
		top: 50%;
		max-height: calc(100% - 80rpx);
		z-index: 101;
		border-radius: 20rpx;
		overflow: hidden;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		padding: 36rpx 0 0 0;
		.preview-panel-header {
			font-size: 36rpx;
			font-weight: 400;
			color: #66645d;
			text-align: center;
			line-height: 50rpx;
			padding: 0 40rpx;
		}
		.preview-panel-body {
			max-width: 590rpx;
			min-height: 591rpx;
			box-shadow: 0 4rpx 20rpx 0 rgba(102, 100, 93, 0.1);
			border-radius: 20rpx;
			margin: 20rpx 40rpx 0 40rpx;
			overflow-y: auto;
			.panel-image {
				width: 100%;
				min-height: 100%;
				vertical-align: middle;
			}
		}
		.preview-panel-footer {
			display: flex;
			margin-top: 40rpx;
			flex-shrink: 0;
			background-color: #f7f7f7;
			button {
				width: 50%;
				border-radius: 0;
				font-size: 30rpx;
				line-height: 90rpx;
				&::after {
					border-radius: 0;
					border: none;
				}
			}
		}
	}
}
</style>
